﻿package game.ui {
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	
	public class Button extends SimpleButton {
		
		public static const UP_STATE:String		= "upState";
		public static const OVER_STATE:String	= "overState";
		public static const DOWN_STATE:String	= "downState";
		
		public function Button():void {
			
			upgradeStates();
		}
		
		private function upgradeStates():void {
			//обновляет кнопку, Shape -> MovieClip
			var mc:MovieClip;
			for each ( var state:String in states ) {
				mc	= new MovieClip;
				mc.addChild ( this[state] );
				this[state]	= mc;
			}
			return;
		}
		
		private function textChanged(event:Event):void {
			var p:MovieClip = event.target.parent as MovieClip;
			var t:Text = event.target as Text;
			if (!p || !t) return;
			
			t.x = (p.width-t.width)/2;
			t.y = (p.height-t.height)/2;
		}
		
		private function get states():Array {
			return [UP_STATE, OVER_STATE, DOWN_STATE];
		}
		
		public function setIDS(IDS:String):void {
			var text:Text;
			for each ( var state:String in states ) {
				text = new Text;
				text.name = 'text';
				text.addEventListener(Event.CHANGE, textChanged);
				(this[state] as MovieClip).addChild(text);
				text.set(IDS);
			}
		}
		
		public function setFormat(state:String, params:String, value:*):void {
			var text:Text = getTextState(state);
			if (!text) return;
			
			text.setFormat(params, value);
		}
		
		private function getTextState(state:String):Text {
			var txt:Text;
			if (this[state]) {
				if ((this[state] as MovieClip).getChildByName('text')) {
					txt = (this[state] as MovieClip).getChildByName('text') as Text;
				}
			}
			return txt;
		}
		
		public override function set enabled (value:Boolean):void { this.alpha = (value ? 1 : 0.3); super.enabled = value; }
	}
}